#include "pageTracker.h"

	PageTracker::PageTracker(string initialUrl, unsigned long long maxLevel)
: maxLevel_(maxLevel), currentLevel_(1)
{	
	addPage(initialUrl, currentLevel_);
	currentLevel_++;
}

void PageTracker::scan()
{
	// a list of all urls that are referenced by pages on the previous level
	list<string> aggregateUrlsReferenced;
	list<string>::iterator itS;  // temporary iterator for aggregateUrlsReferenced

	for (currentLevel_; currentLevel_ <= maxLevel_; currentLevel_++) {
		aggregateUrlsReferenced.clear();

		// go through each page, and add its urls to aggregateUrlsReferenced if it is in the previous level
		for (it = allPages.begin(); it != allPages.end(); it++) {
			if (it -> level_ == (currentLevel_ - 1)) { // if this particular page is at the correct level
				// add its list of urls to our master list
				aggregateUrlsReferenced.merge(it -> urlsReferenced_);
			}
		}

		// go through every url that *should* be on currentLevel, and add it as a page to the currentLevel_
		for (itS = aggregateUrlsReferenced.begin(); itS != aggregateUrlsReferenced.end(); itS++) {
			addPage(*itS, currentLevel_);
		}
	}
}

void PageTracker::addPage(string url, unsigned long long level)
{
	// first make sure that the page doesn't already exist
	bool exists = false;
	for (it = allPages.begin(); it != allPages.end(); it++) {
		if (it -> url_ == url) {
			exists = true;
		}
	}

	// if the page doesn't already exist, add it
	if (!exists) {
		allPages.push_front(Page(url, level));
	}
}


void PageTracker::outputToGrahpviz()
{
	cout << "digraph g {" << endl;
	cout << "    " << "overlap=false" << endl;
	for (it = allPages.begin(); it != allPages.end(); it++) {
		cout << "    ";
		// :TODO: add label tag for the titles, after it is added
		cout << "\"" << it -> url_ << "\"" << ";" << endl;
	}

	list<string>::iterator itS;
	for (it = allPages.begin(); it != allPages.end(); it++) {
		// display the association between each page and the pages it points to
		for (itS = it -> urlsReferenced_.begin(); itS != it -> urlsReferenced_.end(); itS++) {
			cout << "    ";
			cout << "\"" << it -> url_ << "\"" << " -> " << "\"" << *itS << "\"" << ";" << endl;
		}
	}
	cout << "}" << endl;
}

/*
   Page* PageTracker::addPage(string url)
   {
   if (cachedPages_.find(url) != cachedPages_.end()) { // the page already exists
//cout << "page already exists: " << url << endl;
map<string, Page*>::iterator it;
it = cachedPages_.find(url);
// return a pointer to the already-existing page
return (it -> second);
} else { // never-before seen page
//cout << "new page: " << url << endl;
Page * tmpPage = new Page(url, this, 0);
cachedPages_[url] = tmpPage;
return tmpPage;
}
}
*/
